﻿using System;
using System.Collections.Generic;
using System.Text;

using Obsidian.Utils;
using Obsidian.Action;
using Obsidian.Web;
using Obsidian.Edm;
using Obsidian.Runtime;
using Oak.Core;
using Oak.Base;
using Oak.Model;
using Oak.Base.Data;

namespace Oak.Base.Logic
{
    public class AdminLG : OakLG<ISession>
    {

        public AdminLG() : base() { }

        public AdminLG(ISession session) : base(session) { }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <param name="admin"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public string Login(string account, string password, out BsAdminInfo admin, out string msg)
        {
            if (StringUtil.IsNullOrWhiteSpace(account))
            {
                msg = "账号不能为空";
                admin = null;
                return null;
            }
            if (String.IsNullOrEmpty(password))
            {
                msg = "密码不能为空";
                admin = null;
                return null;
            }
            admin = this.GetAdminByAccount(account, out msg);
            if (admin == null) return null;

            if (admin.Status.Value == AdminStatus.Disabled)
            {
                msg = "该账号已被禁用";
                return null;
            }

            string pwdMds = StringUtil.Md5Encrypt(password);

            if (!pwdMds.Equals(admin.Password.Value))
            {
                msg = "密码错误";
                return null;
            }

            string sessionKey;
            try
            {
                sessionKey = OakSession.Set(admin);
            }
            catch (Exception ex)
            {
                string code = Logger.Error(ex);
                msg = "系统错误：" + code;
                return null;
            }
            return sessionKey;
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <param name="sessionKey"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool Logout(out string msg)
        {
            if (!Session.IsLogin)
            {
                msg = "当前未登录";
                return false;
            }

            string sessionKey = Session.SessionKey;
            bool succ;
            try
            {
                succ = OakSession.Remove(sessionKey);
            }
            catch (Exception ex)
            {
                string code = Logger.Error(ex);
                msg = "系统错误：" + code;
                return false;
            }
            msg = "";
            return succ;
        }

        /// <summary>
        /// 创建管理员
        /// </summary>
        /// <param name="admin"></param>
        /// <param name="password"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public BsAdminInfo CreateAdmin(BsAdminInfo admin, string password, out string msg)
        {

            if (!Session.IsSuperAdmin)
            {
                msg = "当前账号没有权限执行该操作";
                return null;
            }

            if (StringUtil.IsNullOrWhiteSpace(password))
            {
                msg = "密码不能为空";
                return null;
            }

            string pwdMd5 = StringUtil.Md5Encrypt(password);

            admin.IsSuperAdmin.Set(false);
            admin.Password.Set(pwdMd5);
            if (admin.Email.IsNullOrWhiteSpace)
                admin.Email.Empty();
            if (admin.MobileNo.IsNullOrWhiteSpace)
                admin.MobileNo.Empty();
            admin.Modified.Now();
            admin.Created.Now();
            admin.Status.Set(AdminStatus.Normal);

            if (!VerifyAdmin(admin, out msg))
                return null;

            string str;
            BsAdminInfo dbAdmin = this.GetAdminByAdminName(admin.AdminName.Value, out str);
            if (dbAdmin != null)
            {
                msg = "该登录账号已存在";
                return null;
            }

            try
            {
                admin.Save();
            }
            catch (Exception ex)
            {
                string code = Logger.Error(ex);
                msg = "保存信息错误：" + code;
                return null;
            }

            msg = "";
            return admin;

        }

        /// <summary>
        /// 修改管理员信息(超级管理员操作)
        /// </summary>
        /// <param name="admin"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public BsAdminInfo Update(BsAdminInfo admin, out string msg)
        {
            if (admin.AdminId.IsNull)
            {
                msg = "adminId参数不能为空";
                return null;
            }

            if (!Session.IsSuperAdmin)
            {
                msg = "当前账号没有权限执行该操作";
                return null;
            }

            BsAdminInfo dbAdmin = this.GetAdminById(admin.AdminId.Value, out msg);
            if (dbAdmin == null)
                return null;

            dbAdmin.ResetAssigned();

            //更新状态
            if (!admin.Status.IsNull)
            {
                if (admin.Status.Value == AdminStatus.Disabled &&
                    dbAdmin.IsSuperAdmin.isTrue())
                {
                    msg = "不能禁用超级管理员账号";
                    return null;
                }
                dbAdmin.Status.Set(admin.Status.Value);
            }

            dbAdmin.Modified.Now();

            try
            {
                dbAdmin.Update();
            }
            catch (Exception ex)
            {
                string code = Logger.Error(ex);
                msg = "发生系统错误:" + code;
                return null;
            }

            msg = "";
            return dbAdmin;

        }

        /// <summary>
        /// 编辑管理员信息(管理员修改自己的信息)
        /// </summary>
        /// <param name="admin"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public BsAdminInfo Edit(BsAdminInfo admin, out string msg)
        {
            BsAdminInfo dbAdmin = this.GetAdminById(Session.AccountId, out msg);
            if (dbAdmin == null)
                return null;

            if (!admin.Email.IsNull)
                dbAdmin.Email.Set(admin.Email.Value);

            if (!admin.MobileNo.IsNull)
                dbAdmin.MobileNo.Set(admin.MobileNo.Value);

            dbAdmin.Modified.Now();

            try
            {
                dbAdmin.Update();
            }
            catch (Exception ex)
            {
                string code = Logger.Error(ex);
                msg = "发生系统错误:" + code;
                return null;
            }

            msg = "";
            return dbAdmin;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="oldPwd">原密码</param>
        /// <param name="newPwd">新密码</param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool ChangePassword(string oldPwd, string newPwd, out string msg)
        {
            if (String.IsNullOrEmpty(oldPwd))
            {
                msg = "原密码不能为空";
                return false;
            }

            if (String.IsNullOrEmpty(newPwd))
            {
                msg = "密码不能为空";
                return false;
            }

            BsAdminInfo dbAdmin = this.GetAdminById(Session.AccountId, out msg);
            if (dbAdmin == null)
                return false;

            string oldPwdMd5 = StringUtil.Md5Encrypt(oldPwd);
            if (!dbAdmin.Password.Value.Equals(oldPwdMd5))
            {
                msg = "原密码错误";
                return false;
            }

            string newPwdMd5 = StringUtil.Md5Encrypt(newPwd);

            dbAdmin.ResetAssigned();
            dbAdmin.Password.Set(newPwdMd5);
            dbAdmin.Modified.Now();

            try
            {
                dbAdmin.Update();
                msg = "";
                return true;
            }
            catch (Exception ex)
            {
                string code = Logger.Error(ex);
                msg = "系统错误:" + code;
                return false;
            }

        }


        public IList<BsAdminInfo> GetAdminList(BsAdminQry qry, out ListAttrInfo listAttr, out string msg)
        {

            if (!Session.IsSuperAdmin)
            {
                msg = "当前账号没有权限执行该操作";
                listAttr = null;
                return null;
            }

            AdminDA adminDA = new AdminDA();
            IList<BsAdminInfo> list = adminDA.SelectAdminList(qry, out listAttr);
            msg = "";
            return list;
        }

        internal BsAdminInfo GetAdminById(long adminId, out string msg)
        {
            BsAdminInfo admin = OModel.GetByPk<BsAdminInfo>(adminId);
            if (admin == null)
            {
                msg = "该管理员信息不存在";
                return null;
            }
            msg = "";
            return admin;
        }

        internal BsAdminInfo GetAdminByAccount(string account, out string msg)
        {
            if (StringUtil.IsMoblie(account))
            {
                return this.GetAdminByMobileNo(account, out msg);
            }
            else if (StringUtil.IsEmail(account))
            {
                return this.GetAdminByEmail(account, out msg);
            }
            else
            {
                return this.GetAdminByAdminName(account, out msg);
            }
        }


        internal BsAdminInfo GetAdminByAdminName(string adminName, out string msg)
        {
            AdminDA adminDA = new AdminDA();
            BsAdminInfo admin = adminDA.SelectAdminByAdminName(adminName);
            if (admin == null)
            {
                msg = "该账号不存在";
                return null;
            }
            msg = "";
            return admin;
        }


        internal BsAdminInfo GetAdminByMobileNo(string mobileNo, out string msg)
        {
            AdminDA adminDA = new AdminDA();
            BsAdminInfo admin = adminDA.SelectAdminByMobileNo(mobileNo);
            if (admin == null)
            {
                msg = "该账号不存在";
                return null;
            }
            msg = "";
            return admin;
        }

        internal BsAdminInfo GetAdminByEmail(string email, out string msg)
        {
            AdminDA adminDA = new AdminDA();
            BsAdminInfo admin = adminDA.SelectAdminByEmail(email);
            if (admin == null)
            {
                msg = "该账号不存在";
                return null;
            }
            msg = "";
            return admin;
        }

        private bool VerifyAdmin(BsAdminInfo admin, out string msg)
        {
            if (admin.AdminName.IsNullOrWhiteSpace)
            {
                msg = "登录名不能为空";
                return false;
            }
            string adminName = admin.AdminName.Value;
            if (adminName.Length > 12)
            {
                msg = "登录名长度不能超过12";
                return false;
            }
            
            if (!admin.Email.IsNullOrEmpty &&
               !StringUtil.IsEmail(admin.Email.Value))
            {
                msg = "邮箱格式不正确";
                return false;
            }

            if (!admin.MobileNo.IsNullOrEmpty &&
                !StringUtil.IsMoblie(admin.MobileNo.Value))
            {
                msg = "手机号码格式不正确";
                return false;
            }

            msg = "";
            return true;
        }

    }
}
